using Catalog.Application.Brands.Interfaces;
using Catalog.Application.CatalogItems.Interfaces;
using Catalog.Application.Categorys.Interfaces;
using Catalog.Application.Interfaces;
using Catalog.Infrastructure.Persistence.ReadServices;
using Catalog.Infrastructure.Repositories;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using BuildingBlocks.Infrastructure.EventBus.RabbitMQ;
using Catalog.Infrastructure.HostedService;
using BuildingBlocks.Abstractions.Permissions;
using Catalog.Infrastructure.GrpcClients;
using Catalog.Application.Contracts;
using Catalog.Infrastructure.Caching;
using StackExchange.Redis;
using PermissionCenter.Grpc;


namespace Catalog.Infrastructure;

public static class ServiceCollectionExtensions
{
    public static IServiceCollection AddCatalogInfrastructure(this IServiceCollection services, IConfiguration configuration)
    {
        services.AddDbContext<CatalogDbContext>(options =>
            options.UseNpgsql(configuration.GetConnectionString("Default")));

        services.AddEventBus(configuration);
        services.AddScoped<ICatalogItemReadService, CatalogItemReadService>();
        services.AddScoped<ICatalogItemRepository, CatalogItemRepository>();
        services.AddScoped<ICategoryReadService, CategoryReadService>();
        services.AddScoped<ICategoryRepository, CategoryRepository>();
        services.AddScoped<IBrandReadService, BrandReadService>();
        services.AddScoped<IBrandRepository, BrandRepository>();
        services.AddScoped<IUnitOfWork, UnitOfWork>();
        services.AddHostedService<CatalogStartupTasks>();

        services.AddSingleton<IPermissionCenterClient>(sp =>
        {
            // 读取配置文件中的 URL
            var config = sp.GetRequiredService<IConfiguration>();
           
            var permissionCenterUrl = config["Grpc:PermissionCenterUrl"];   // e.g. https://localhost:5212

            // 创建客户端实例（内部会创建 gRPC Channel 并跳过自签名证书验证）
            return new PermissionCenterGrpcClient(permissionCenterUrl);
        });
        services.AddSingleton<IPermissionBindingServiceClient>(sp =>
        {
            // 读取配置文件中的 URL
            var config = sp.GetRequiredService<IConfiguration>();
            var permissionBindingUrl = config["Grpc:PermissionBindingUrl"]; // e.g. https://localhost:5211
          

            // 创建客户端实例（内部会创建 gRPC Channel 并跳过自签名证书验证）
            return new PermissionBindingServiceGrpcClient(permissionBindingUrl);
        });

        services.AddSingleton<IRedisService>(sp =>
       {
           var config = configuration.GetConnectionString("Redis");
           return new RedisService(config!);
       });


        return services;
    }
}